<template>
  <div class="patient-dashboard-container">
    <h2 class="page-title">患者个人中心</h2>

    <el-row :gutter="20" class="overview-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="overview-card animated-fade-in">
          <div class="overview-item">
            <el-icon class="overview-icon visit-count-icon"><List /></el-icon>
            <div class="overview-content">
              <div class="overview-title">累计就诊次数</div>
              <div class="overview-value">{{ visitCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="overview-card animated-fade-in delay-1">
          <div class="overview-item">
            <el-icon class="overview-icon latest-visit-icon"><Clock /></el-icon>
            <div class="overview-content">
              <div class="overview-title">最近就诊日期</div>
              <div class="overview-value">{{ formatLatestVisitDate(latestVisitDate) || '暂无' }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="overview-card animated-fade-in delay-2">
          <div class="overview-item">
            <el-icon class="overview-icon diagnosis-count-icon"><Files /></el-icon>
            <div class="overview-content">
              <div class="overview-title">累计诊断数</div>
              <div class="overview-value">{{ diagnosisCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card shadow="hover" class="overview-card animated-fade-in delay-3">
          <div class="overview-item">
            <el-icon class="overview-icon favorite-doctor-icon"><Star /></el-icon>
            <div class="overview-content">
              <div class="overview-title">关注医生</div>
              <div class="overview-value">{{ favoriteDoctor || '未指定' }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="hover" class="recent-visits-card animated-fade-in delay-4">
      <template #header>
        <div class="card-header">
          <span>最近三次就诊记录</span>
          <el-button link type="primary" :icon="More" @click="goToConsultations">查看更多</el-button>
        </div>
      </template>
      <el-table
          v-loading="loading"
          :data="recentVisits"
          stripe
          border
          style="width: 100%;"
          class="custom-table"
      >
        <el-table-column prop="visitDate" label="就诊日期" width="160" sortable align="center">
          <template #default="{ row }">
            {{ formatDate(row.visitDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="diagnosis" label="诊断" min-width="200" show-overflow-tooltip />
        <el-table-column prop="prescription" label="处方" min-width="200" show-overflow-tooltip />
        <el-table-column prop="hospitalName" label="就诊医院" width="150" show-overflow-tooltip />
        <el-table-column prop="doctorName" label="就诊医生" width="120" />
      </el-table>
      <el-empty v-if="!loading && recentVisits.length === 0" description="暂无就诊记录"></el-empty>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { List, Clock, Files, Star, More } from '@element-plus/icons-vue' // Import Element Plus icons

const router = useRouter()

// --- Data Definitions ---
const visitCount = ref(0)
const latestVisitDate = ref('')
const diagnosisCount = ref(0)
const favoriteDoctor = ref('') // Assume this can be fetched from the backend

const recentVisits = ref([])
const loading = ref(true)

// --- Methods ---

const fetchDashboardData = async () => {
  const patientId = localStorage.getItem('userId')
  if (!patientId) {
    ElMessage.error('未找到患者ID，请重新登录')
    loading.value = false
    return
  }

  loading.value = true
  try {
    // Assuming this endpoint fetches all visit records for the current patient
    const res = await axios.get(`http://localhost:8080/visits/${patientId}`)
    const visits = Array.isArray(res.data.data) ? res.data.data : (res.data.data ? [res.data.data] : []); // Handle single object vs array

    // Cumulative Visit Count
    visitCount.value = visits.length

    if (visits.length > 0) {
      // Sort visit records by date in descending order to get the latest
      const sortedVisits = [...visits].sort((a, b) => new Date(b.visitDate) - new Date(a.visitDate))

      // Latest Visit Date
      latestVisitDate.value = sortedVisits[0].visitDate

      // Cumulative Diagnosis Count: Filter records with non-empty diagnosis
      diagnosisCount.value = visits.filter(v => v.diagnosis && v.diagnosis.trim() !== '').length

      // Recent 3 Visit Records
      // Assuming backend data includes hospitalName and doctorName
      recentVisits.value = sortedVisits.slice(0, 3).map(visit => ({
        ...visit,
        hospitalName: visit.hospitalName || '未知医院', // Example default value
        doctorName: visit.doctorName || '未知医生' // Example default value
      }))
    } else {
      // Reset counts and records if no visits are found
      latestVisitDate.value = ''
      diagnosisCount.value = 0
      recentVisits.value = []
    }

    // Example: Fetch favorite doctor from a user configuration API
    // const userConfigRes = await axios.get(`http://localhost:8080/user/config/${patientId}`);
    // favoriteDoctor.value = userConfigRes.data?.data?.favoriteDoctorName || '未指定';
    favoriteDoctor.value = '张医生' // Hardcoded example
  } catch (error) {
    console.error('获取仪表盘数据失败', error)
    ElMessage.error('获取仪表盘数据失败，请检查网络或服务器。')
  } finally {
    loading.value = false
  }
}

// Function to format date display (e.g., YYYY-MM-DD)
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString);
  if (isNaN(date.getTime())) {
    return dateString; // Return original string if not a valid date
  }
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
}

// Function to format latest visit date (e.g., "Today", "Yesterday", "X days ago", or YYYY-MM-DD)
const formatLatestVisitDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString);
  if (isNaN(date.getTime())) {
    return dateString;
  }
  const now = new Date();
  const diffTime = Math.abs(now.getTime() - date.getTime());
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  if (diffDays === 0) return '今天';
  if (diffDays === 1) return '昨天';
  if (diffDays < 7) return `${diffDays}天前`;
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
}

// Navigate to the full consultation records page
const goToConsultations = () => {
  router.push('/home/consultations') // Assuming your consultation list page route is this
}

// --- Lifecycle Hook ---
onMounted(() => {
  fetchDashboardData()
})
</script>

<style scoped>
.patient-dashboard-container {
  padding: 30px; /* Page inner padding */
  background-color: #f8fbfd; /* Page background color */
  min-height: calc(100vh - 60px); /* Adjust height for main layout */
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 30px;
  text-align: center;
  position: relative;
}

.page-title::after {
  content: '';
  position: absolute;
  left: 50%;
  bottom: -10px;
  transform: translateX(-50%);
  width: 60px;
  height: 4px;
  background-color: #67C23A; /* Green line */
  border-radius: 2px;
}

/* Overview Card Area */
.overview-cards {
  margin-bottom: 30px;
}

.overview-card {
  border-radius: 12px; /* Rounded card corners */
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08); /* Soft shadow */
  transition: all 0.3s ease; /* Hover animation */
  background-color: #fff; /* Ensure white background */
}

.overview-card:hover {
  transform: translateY(-5px); /* Lift on hover */
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12); /* Deeper shadow on hover */
}

.overview-item {
  display: flex;
  align-items: center;
  justify-content: center; /* Center content */
  padding: 10px 0;
}

.overview-icon {
  font-size: 42px; /* Icon size */
  margin-right: 15px;
  width: 58px; /* Ensure consistent icon container size */
  height: 58px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%; /* Circular icon background */
  color: #fff; /* Icon color */
  box-shadow: 0 4px 10px rgba(0,0,0,0.1);
  flex-shrink: 0; /* Prevent icon from shrinking */
}

/* Set background colors for different icons */
.visit-count-icon { background: linear-gradient(135deg, #409EFF 0%, #66B1FF 100%); } /* Blue gradient */
.latest-visit-icon { background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%); } /* Green gradient */
.diagnosis-count-icon { background: linear-gradient(135deg, #E6A23C 0%, #F3D19E 100%); } /* Orange gradient */
.favorite-doctor-icon { background: linear-gradient(135deg, #F56C6C 0%, #FA8D8D 100%); } /* Red gradient */


.overview-content {
  text-align: left; /* Align content to the left */
}

.overview-title {
  font-size: 16px;
  color: #666;
  margin-bottom: 5px; /* Reduced space between title and value */
  font-weight: 500;
}

.overview-value {
  font-size: 32px; /* Larger value font size */
  font-weight: bold;
  color: #333;
  letter-spacing: 1px; /* Letter spacing */
}

/* Recent Visits Card */
.recent-visits-card {
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  background-color: #fff;
}

.recent-visits-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}

.recent-visits-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5; /* Title underline */
}

/* Table Styles */
.custom-table {
  border-radius: 8px; /* Table rounded corners */
  overflow: hidden; /* Ensure rounded corners are applied */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03); /* Light table shadow */
}

.custom-table :deep(.el-table__header-wrapper th) {
  background-color: #f2f6fc; /* Table header background color */
  color: #555;
  font-weight: 600;
  padding: 12px 0; /* Table header cell padding */
}

.custom-table :deep(.el-table__cell) {
  padding: 10px 0; /* Table cell padding */
}

.el-empty {
  padding: 30px 0;
}

/* Entry Animation */
.animated-fade-in {
  opacity: 0;
  transform: translateY(20px);
  animation: fadeInMoveUp 0.6s ease-out forwards;
}

.delay-1 { animation-delay: 0.1s; }
.delay-2 { animation-delay: 0.2s; }
.delay-3 { animation-delay: 0.3s; }
.delay-4 { animation-delay: 0.4s; } /* For the table */

@keyframes fadeInMoveUp {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>